package com.kk.controller;

import com.kk.entity.User;
import com.kk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/")
    public String index() {
        return "login";
    }
    
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       HttpSession session,
                       Model model) {
        User user = userService.login(username, password);
        if (user == null) {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
        
        session.setAttribute("user", user);

        
        // 根据角色跳转到不同的页面
        switch (user.getRole()) {
            case "STUDENT":
                return "redirect:/student/index";
            case "DOCTOR":
                return "redirect:/doctor/index";
            case "COUNSELOR":
                return "redirect:/counselor/index";
            case "TEACHER":
                return "redirect:/teacher/index";
            default:
                model.addAttribute("error", "未知的用户角色");
                return "login";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
} 